<script setup lang="ts">
  import sourceTable from '@/components/sourceTable/index.vue';
  import sourceAddFrame from '@/components/sourceAddFrame/index.vue';
  import { useDatasourceQuery, useSourceAddAndEdit } from './hooks/vector';
  import {SM4Util} from '@/utils/sm4encry.js'
  import { registerDatasource, validates } from '@/api/datasource';
  import { ElMessage } from 'element-plus';

  const { sourceList, sourceTotal, queryParameters, getSourceTable, pageChange, queryChange,deleteSource } = useDatasourceQuery();
  const { addFrameShow, dataSourceTypes, dataTypes, sourceAddParams, sourceType, openAddFrame } = useSourceAddAndEdit();

  getSourceTable();

  /**
   * @function sourceNewAdd 添加数据源函数
   * @description 用于接收组件传出的参数判断是否能够连接成功，然后进行注册数据源
   * @param parameter {any} 传进来的参数
   */
  const sourceNewAdd = async (parameter:any) =>{
    const {user,type,password,name,port,ip,database,remark,typeCode} = parameter
    const validatesParams = {
      config:JSON.stringify({port,ip,database}),
      name,
      password:SM4Util.encryptData_ECB(password),
      type,
      user,
    }
    const res:any = await validates(validatesParams)
    if (res.status === 200){
      const registerParams = { ...validatesParams,remark,typeCode }
      const createRes:any = await registerDatasource(registerParams)
      if (createRes.status === 200){
        ElMessage({
          message: createRes.msg,
          type:'success'
        })
        addFrameShow.value = false
        // TODO:: 组合式函数中不能互相调用方法，是否可以用什么操作来解决？
        // READ:: 这里暂时没有找到更好的办法，通过参数把方法传进组合式函数中,不能直接从useDatasourceQuery实例化，方法会存在问题，这里选择把方法移出来
        getSourceTable()
      } else {
        ElMessage({
          message: createRes.msg,
          type: 'error'
        })
      }
    } else {
      ElMessage({
        message: res.msg,
        type: 'error'
      })
    }
  }

</script>

<template>
  <div class="vector-box">
    <source-table
      :table="sourceList"
      :total="sourceTotal"
      :current-page="queryParameters.page"
      :page-size="queryParameters.rows"
      @on-delete='deleteSource'
      @on-query-change="queryChange"
      @on-open-add="openAddFrame"
      @on-page-change="pageChange" />
    <source-add-frame
      title="添加数据源"
      v-if="addFrameShow"
      :data-types="dataTypes"
      :add-params="sourceAddParams"
      v-model:source-type="sourceType"
      @on-new-add='sourceNewAdd'
      :source-type-list="dataSourceTypes"></source-add-frame>
  </div>
</template>

<style scoped lang="less">
  .vector-box {
    width: 100%;
    height: 100%;
  }
</style>
